package com.wanxi.spring.cloud.zuul.config;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.zuul.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class PreLogFilter extends ZuulFilter {

    @Value("#{'${pathlist}'.split(',')}")
    private List<String> pathlist;
    @Value("#{'${havetoken}'.split(',')}")
    private List<String> havetoken;

    @Autowired
    UserService userService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        //那些路径可以直接放行
        boolean a = pathlist.stream().anyMatch(path -> StringUtils.contains(uri, path));
        if (!a) {//如果不是可放行路径
            CommonResult result = userService.sendToken(request);//判断是否携带有效的token
            if (result.getCode() == 200) {//如果携带有效的token
                //判断是否是所有用户都拥有的基本权限
                boolean isBase = havetoken.stream().anyMatch(path -> StringUtils.contains(uri, path));
                if (!isBase) {//如果该请求不是基本权限
                    //判断该用户是否有基本请求外的权限
                    UserDetails data = (UserDetails) result.getData();
                    List<String> collect = data.getAuthorities().stream().map(auz -> auz.getAuthority()).collect(Collectors.toList());
                    boolean b = collect.stream().anyMatch(p -> StringUtils.contains(uri, p));
                    if (!b) {//如果没有则拦截
                        requestContext.setResponseBody(JSON.toJSONString(CommonResult.unauthorized("您暂时没有该权限")));
                        requestContext.setSendZuulResponse(false);
                    }
                }
            } else {
                requestContext.setResponseBody(JSON.toJSONString(result));
                requestContext.setSendZuulResponse(false);
            }
        }
        return null;
    }
}
